/*
 * FOF资产策略配置图表模块
 */
require('!style!css!../css/configGraph.css');
var combinationGraphHtml = require('!html!../html/combinationGraph.html');
var common = require('./common.js');
var loading = require('./loading.js');
var page = require('./page.js');
var show = require('./show.js');
//require('./cov.js');
var combinationGraphVue;
var combinationGraph = {
    myChart: null,
    combinationEChart: null,
    hasLoaded: false,
    jsonData: null,
    paramJson: null,
    init: function (paramJson) {
        combinationGraph.paramJson = paramJson;
        page.setPage(7);
        common.initNav(4);
        $('.step').hide();
        $('#combinationGraph').html(combinationGraphHtml).show();
        this.initCallback();
        loading.start();
        common.getData({
            path: 'assetOrStrategyStart',
            callback: 'loadAssetOrStrategyStartResultCombination',
            extra: '?calType=2&params=' + encodeURIComponent(JSON.stringify(paramJson))
        });
    },
    isCustomWeight: function () {
        return combinationGraph.paramJson.modelId == 4;
    },
    setTimeoutLoadResult: function () {
        setTimeout(function () {
            if (combinationGraph.isCustomWeight()) {
                common.getData({
                    path: 'assetOrStrategyResultCustom',
                    callback: 'loadAssetOrStrategyResultCombinationCustom',
                    extra: '?calType=2&taskId=' + window['combinationTaskId']
                });
            } else {
                common.getData({
                    path: 'assetOrStrategyResult',
                    callback: 'loadAssetOrStrategyResultCombination',
                    extra: '?calType=2&taskId=' + window['combinationTaskId']
                });
            }
        }, 2000);
    },
    initCallback: function () {
        page.initSelectedParams(7);
        window['loadAssetOrStrategyResultCombinationShow'] = false;
        combinationGraph.hasLoaded = false;
        window['loadAssetOrStrategyStartResultCombination'] = function (json) {
            var taskId = common.filterData(json, 'taskId');
            if (taskId) {
                window['combinationTaskId'] = taskId;
                combinationGraph.setTimeoutLoadResult();
            }
        };
        window['loadAssetOrStrategyResultCombination'] = window['loadAssetOrStrategyResultCombinationCustom'] = function (json) {
            if (!json || !json.code || json.code == -2 || json.code == -3) {
                //计算失败 未查到任务
                alert('计算异常，错误码：' + json.code);
                return;
            }
            if (window.location.href.indexOf('testCombination=1') > -1) {
                //json = big;
                json = covObj;
                var testFundList = [{
                    "accumulateNav": 0,
                    "drawdown": 0,
                    "filterStatus": 1,
                    "fundBenchmarkId": 0,
                    "fundExtCode": "270031",
                    "fundExtSource": 2,
                    "fundFundationDate": "2017-01-25 00:00:00",
                    "fundIssuingSacle": 0,
                    "fundManagementCompany": "东吴证券资管",
                    "fundManager": "",
                    "fundNameFull": "东吴汇利12号集合资产管理计划",
                    "fundNameShort": "东吴汇利12号",
                    "fundStatus": 1,
                    "fundStrategyId": 0,
                    "fundTypeHedging": "非对冲",
                    "fundTypeQuant": "非量化",
                    "fundTypeStrategy": "债券基金",
                    "fundTypeTarget": "债券等固定收益",
                    "lastUpdateDate": "2017-04-19 00:00:00",
                    "sharpRatio": 105.39,
                    "unitNav": 0,
                    "volatilityAnnually": 0,
                    "yield1y": 0.02,
                    "yield3y": 0.02,
                    "yield5y": 0.02,
                    "yieldAnnually": 0.02
                }, {
                    "accumulateNav": 0,
                    "drawdown": 0,
                    "filterStatus": 1,
                    "fundBenchmarkId": 0,
                    "fundExtCode": "7670",
                    "fundExtSource": 2,
                    "fundFundationDate": "2012-04-27 00:00:00",
                    "fundIssuingSacle": 0,
                    "fundManagementCompany": "银河金汇证券资管",
                    "fundManager": "魏琦",
                    "fundNameFull": "中国银河证券水星2号集合资产管理计划",
                    "fundNameShort": "银河水星2号",
                    "fundStatus": 1,
                    "fundStrategyId": 0,
                    "fundTypeHedging": "非对冲",
                    "fundTypeQuant": "非量化",
                    "fundTypeStrategy": "股票多头",
                    "fundTypeTarget": "货币型",
                    "lastUpdateDate": "2017-04-10 00:00:00",
                    "sharpRatio": 66.55,
                    "unitNav": 0,
                    "volatilityAnnually": 0,
                    "yield1y": 0.04,
                    "yield3y": 0.04,
                    "yield5y": 0.03,
                    "yieldAnnually": 0.03
                }, {
                    "accumulateNav": 0,
                    "drawdown": 0,
                    "filterStatus": 1,
                    "fundBenchmarkId": 0,
                    "fundExtCode": "33609",
                    "fundExtSource": 2,
                    "fundFundationDate": "2014-12-03 00:00:00",
                    "fundIssuingSacle": 0,
                    "fundManagementCompany": "联讯证券资管",
                    "fundManager": "叶进",
                    "fundNameFull": "联讯证券天天利1号集合资产管理计划",
                    "fundNameShort": "联讯天天利1号",
                    "fundStatus": 1,
                    "fundStrategyId": 0,
                    "fundTypeHedging": "非对冲",
                    "fundTypeQuant": "非量化",
                    "fundTypeStrategy": "组合基金",
                    "fundTypeTarget": "货币型",
                    "lastUpdateDate": "2017-04-20 00:00:00",
                    "sharpRatio": 57.47,
                    "unitNav": 0,
                    "volatilityAnnually": 0,
                    "yield1y": 0.02,
                    "yield3y": 0.03,
                    "yield5y": 0.03,
                    "yieldAnnually": 0.03
                }, {
                    "accumulateNav": 0,
                    "drawdown": 0,
                    "filterStatus": 1,
                    "fundBenchmarkId": 0,
                    "fundExtCode": "258710",
                    "fundExtSource": 2,
                    "fundFundationDate": "2016-12-05 00:00:00",
                    "fundIssuingSacle": 0,
                    "fundManagementCompany": "中信证券资管",
                    "fundManager": "",
                    "fundNameFull": "中信证券瑞盛1号（年系列）集合资产管理计划",
                    "fundNameShort": "中信证券瑞盛1号(年系列)",
                    "fundStatus": 1,
                    "fundStrategyId": 0,
                    "fundTypeHedging": "非对冲",
                    "fundTypeQuant": "非量化",
                    "fundTypeStrategy": "债券基金",
                    "fundTypeTarget": "债券等固定收益",
                    "lastUpdateDate": "2017-04-20 00:00:00",
                    "sharpRatio": 55.36,
                    "unitNav": 0,
                    "volatilityAnnually": 0,
                    "yield1y": 0.03,
                    "yield3y": 0.03,
                    "yield5y": 0.03,
                    "yieldAnnually": 0.03
                }, {
                    "accumulateNav": 0,
                    "drawdown": 0,
                    "filterStatus": 1,
                    "fundBenchmarkId": 0,
                    "fundExtCode": "38741",
                    "fundExtSource": 2,
                    "fundFundationDate": "2015-01-13 00:00:00",
                    "fundIssuingSacle": 0,
                    "fundManagementCompany": "国泰君安资管",
                    "fundManager": "",
                    "fundNameFull": "国泰君安君得金优先级专项资产管理计划优先级365天（第五期）",
                    "fundNameShort": "君得金优先级365天（第五期）",
                    "fundStatus": 1,
                    "fundStrategyId": 0,
                    "fundTypeHedging": "非对冲",
                    "fundTypeQuant": "非量化",
                    "fundTypeStrategy": "债券基金",
                    "fundTypeTarget": "债券等固定收益",
                    "lastUpdateDate": "2017-04-21 00:00:00",
                    "sharpRatio": 51.65,
                    "unitNav": 0,
                    "volatilityAnnually": 0,
                    "yield1y": 0.05,
                    "yield3y": 0.05,
                    "yield5y": 0.05,
                    "yieldAnnually": 0.05
                }, {
                    "accumulateNav": 0,
                    "drawdown": 0,
                    "filterStatus": 1,
                    "fundBenchmarkId": 0,
                    "fundExtCode": "31619",
                    "fundExtSource": 2,
                    "fundFundationDate": "2014-11-11 00:00:00",
                    "fundIssuingSacle": 0,
                    "fundManagementCompany": "国泰君安资管",
                    "fundManager": "",
                    "fundNameFull": "国泰君安君得金优先级专项资产管理计划优先级365天（第三期）",
                    "fundNameShort": "君得金优先级365天（第三期）",
                    "fundStatus": 1,
                    "fundStrategyId": 0,
                    "fundTypeHedging": "非对冲",
                    "fundTypeQuant": "非量化",
                    "fundTypeStrategy": "债券基金",
                    "fundTypeTarget": "债券等固定收益",
                    "lastUpdateDate": "2017-04-21 00:00:00",
                    "sharpRatio": 51.22,
                    "unitNav": 0,
                    "volatilityAnnually": 0,
                    "yield1y": 0.05,
                    "yield3y": 0.05,
                    "yield5y": 0.05,
                    "yieldAnnually": 0.05
                }, {
                    "accumulateNav": 0,
                    "drawdown": 0,
                    "filterStatus": 1,
                    "fundBenchmarkId": 0,
                    "fundExtCode": "173762",
                    "fundExtSource": 2,
                    "fundFundationDate": "2016-02-04 00:00:00",
                    "fundIssuingSacle": 0,
                    "fundManagementCompany": "植瑞投资",
                    "fundManager": "",
                    "fundNameFull": "植瑞现金管理2号",
                    "fundNameShort": "植瑞现金管理2号",
                    "fundStatus": 1,
                    "fundStrategyId": 0,
                    "fundTypeHedging": "非对冲",
                    "fundTypeQuant": "非量化",
                    "fundTypeStrategy": "债券基金",
                    "fundTypeTarget": "债券等固定收益",
                    "lastUpdateDate": "2017-04-20 00:00:00",
                    "sharpRatio": 51.07,
                    "unitNav": 0,
                    "volatilityAnnually": 0,
                    "yield1y": 0.05,
                    "yield3y": 0.05,
                    "yield5y": 0.05,
                    "yieldAnnually": 0.05
                }];
                window['fundCheckList'] = testFundList;
            }
            if (json && json.code != 200) {
                combinationGraph.setTimeoutLoadResult();
                return;
            }
            combinationGraph.jsonData = json;
            if (combinationGraph.isCustomWeight()) {
                loading.end();
                $('#combinationPointContent').hide();
                var configModel = $('#combination').find('.config-model');
                var configModelInput = configModel.find('input');
                $('#combinationGraphGraph').html('<div class="config-model" style="width: 95%;">' + configModel.html() + '</div>');
                $('#combinationGraphGraph').find('.config-model').find('input').each(function (i) {
                    $(this).val(configModelInput.eq(i).val()).attr('disabled', 'true');
                });
                combinationGraph.goECharts(json);
                combinationGraphVue = new Vue({
                    el: '#combinationGraph',
                    data: {
                        fundList: window['fundCheckList']
                    },
                    methods: {
                        accept: function () {
                            combinationGraph.next();
                        },
                        covMore: function () {
                            common.enlargeCov();
                        }
                    }
                });
                combinationGraph.initCov();
                return;
            }
            $('#combinationPointContent').show();
            var data = common.filterData(json, 'pointList');
            if (data) {
                if (window['loadAssetOrStrategyResultCombinationShow']) {
                    return;
                } else {
                    window['loadAssetOrStrategyResultCombinationShow'] = true;
                }
            }
            var pointList = data;
            $.each(pointList, function (k, v) {
                $.each(v, function (kk, vv) {
                    if (typeof vv != 'object') {
                        pointList[k][kk] = parseFloat(parseFloat(vv) * 100).toFixed(2);
                    }
                });
            });
            loading.end();
            combinationGraph.showGraph(pointList);
            combinationGraph.goECharts(json);
        };
        window['createResult'] = function (json) {
            console.log('createResult', json);
            loading.end();
            var fofId = common.filterData(json, 'fofId');
            if (fofId) {
                show.init(fofId);
            } else {
                alert('保存FOF失败');
            }
        };
    },
    initCov: function () {
        try {
            var cov = combinationGraph.jsonData.data.cov;
            var fundListLength = window['fundCheckList'].length;
            $('.cov').each(function (i) {
                console.log('cov' + i, parseFloat(cov[i]).toFixed(4));
                $(this).html(parseFloat(cov[i]).toFixed(4));
            });
            for (var i = 0; i < fundListLength - 1; i++) {
                for (var j = fundListLength * i + (i + 1); j < fundListLength * (i + 1); j++) {
                    $('.cov').eq(j).html('');
                }
            }
        } catch (e) {
        }
    },
    showGraph: function (data) {
        if (combinationGraph.hasLoaded) {
            return false;
        }
        $('#combinationGraphGraph').html('');
        var dom = document.getElementById('combinationGraphGraph');
        this.myChart = echarts.init(dom);
        var myChart = this.myChart;
        option = null;
        option = {
            title: {
                text: '收益风险图',
                left: 'center'
            },
            grid: {
                left: '3%',
                right: '15%',
                bottom: '3%',
                containLabel: true
            },
            tooltip: {
                trigger: 'axis',
                showDelay: 0,
                formatter: function (params) {
                    if (params.value.length > 1) {
                        var other = '';
                        return params.seriesName + ':<br>'
                            + '风险：' + params.value[0] + '%<br>'
                            + '收益：' + params.value[1] + '%<br>'
                            + other;
                    }
                },
                axisPointer: {
                    show: true,
                    type: 'cross',
                    crossStyle: {
                        type: 'dashed',
                        width: 1
                    }
                }
            },
            toolbox: {
                show: false,
                feature: {
                    dataZoom: {},
                    brush: {
                        type: ['rect', 'polygon', 'clear']
                    }
                }
            },
            brush: {},
            legend: {
                show: false,
                data: ['收益风险图'],
                left: 'center'
            },
            xAxis: [
                {
                    name: '风险值(%)',
                    type: 'value',
                    scale: true,
                    axisLabel: {
                        formatter: '{value}'
                    },
                    splitLine: {
                        show: false
                    }
                }
            ],
            yAxis: [
                {
                    name: '收益值(%)',
                    type: 'value',
                    scale: true,
                    axisLabel: {
                        formatter: '{value}'
                    },
                    splitLine: {
                        show: false
                    }
                }
            ],
            series: [
                {
                    name: '相关参数值',
                    type: 'scatter',
                    symbolSize: 5,
                    data: data
                }
            ]
        };

        if (option && typeof option === 'object') {
            combinationGraph.hasLoaded = true;
            myChart.setOption(option, true);
            myChart.on('click', function (params) {
                console.log('click', params);
                if (params.componentType == 'series') {
                    console.log('dataIndex:' + params.dataIndex);
                    if (typeof params.dataIndex != 'undefined') {
                        combinationGraph.highlight(params.dataIndex);
                        combinationGraphVue.graphList = [combinationGraphVue.graphAll[params.dataIndex]];
                        combinationGraphVue.dotSelect = true;
                        combinationGraphVue.dot.dataIndex = params.dataIndex;
                        combinationGraphVue.dot.risk = params.data[0] + '%';
                        combinationGraphVue.dot.profit = params.data[1] + '%';
                        combinationGraph.createNewLine(params.dataIndex);
                        console.log(combinationGraphVue.graphList);
                    }
                }
            });
            myChart.on('mouseout', function (params) {
                console.log('mouseout', params);
                if (params.componentType == 'series') {
                    if (typeof params.dataIndex != 'undefined') {
                        if (combinationGraphVue.dot.dataIndex > -1) {
                            combinationGraph.highlight(combinationGraphVue.dot.dataIndex);
                        }
                    }
                }
            });
        }
        var titleList = [];
        $.each(data[0][2], function (k, v) {
            titleList.push(k);
        });
        combinationGraphVue = new Vue({
            el: '#combinationGraph',
            data: {
                titleList: titleList,
                graphAll: data,
                graphList: [],
                dotSelect: false,
                dot: {
                    dataIndex: -1,
                    risk: '',
                    profit: ''
                },
                fundList: window['fundCheckList']
            },
            methods: {
                selectDot: function (e) {
                    var thisObj = $(e.target);
                    thisObj.addClass('on').siblings().removeClass('on');
                    combinationGraph.highlight(thisObj.index());
                },
                accept: function () {
                    combinationGraph.next();
                },
                covMore: function () {
                    common.enlargeCov();
                }
            }
        });
        this.initCov();
    },
    next: function () {
        console.log('combination accept click...');
        if ($('.graph_0').size() == 0) {
            alert('请选择一行数据');
            return false;
        }
        var paramJson = this.paramJson;
        //var fundList = paramJson.upDownParams;
        var fundList = window['fundCheckList'];
        var newParams = {fundList: []};
        $.each(fundList, function (k, v) {
            console.log(v.fundExtCode, v.fundNameShort);
            var obj = {
                id: v.fundExtCode,
                weight: $('.graph_0 td').eq(k + 1).html()
            };
            newParams.fundList.push(obj);
        });
        console.log(combinationGraphVue.graphList);
        var fofName = prompt('请输入FOF名字', '');
        if (fofName != null && fofName != '') {
            fofName = $.trim(fofName);
            if (!fofName) {
                return;
            }
            newParams['fofName'] = fofName;
            window['combinationGraphDot'] = combinationGraphVue.dot;
            loading.start();
            common.getData({
                path: 'create',
                callback: 'createResult',
                extra: '?params=' + encodeURIComponent(JSON.stringify(newParams))
            });
        }
    },
    highlight: function (index) {
        var myChart = this.myChart;
        if (myChart) {
            myChart.dispatchAction({
                type: 'downplay'
            });
            myChart.dispatchAction({
                type: 'highlight',
                dataIndex: index
            });
        }
    },
    resetData: function (data) {
        var bigJSON = {};
        var dataArray = [];
        var nameArray = [];
        $.each(data, function (k, v) {
            nameArray.push(v.name);
        });
        $.each(data[0].priceList, function (k, v) {
            var childArray = [];
            childArray.push(v.date);
            $.each(nameArray, function (kk, vv) {
                childArray.push(data[kk].priceList[k].price / data[kk].priceList[0].price);
            });
            dataArray.push(childArray);
        });
        bigJSON.dataArray = dataArray;
        bigJSON.nameArray = nameArray;
        return bigJSON;
    },
    goECharts: function (json) {
        this.combinationEChart = common.createECharts({
            json: json,
            bigJSONFunction: function (jsondata) {
                return combinationGraph.resetData(common.filterData(jsondata, 'fundPriceTrend'));
            },
            domId: 'combinationECharts',
            text: '基金曲线图',
            precision: 4
        });
    },
    createNewLine: function (pointIndex) {
        try {
            pointIndex = pointIndex || 0;
            var myChart = this.combinationEChart;
            var option = myChart.getOption();
            var series = option.series;
            var newValues = [];
            var pointList = this.jsonData.data.pointList;
            var lineSourceLength = this.jsonData.data.fundPriceTrend.length;
            var bigNumArray = [];
            $.each(series, function (k, v) {
                if (k >= lineSourceLength) {
                    return true;
                }
                var name = v.name;
                var data = v.data;
                var numArray = [];
                $.each(data, function (kk, vv) {
                    var num = parseFloat(pointList[pointIndex][2][name]) * parseFloat(vv);
                    numArray.push(num);
                });
                bigNumArray.push(numArray);
            });
            $.each(series[0].data, function (k, v) {
                $.each(bigNumArray, function (kk, vv) {
                    if (typeof newValues[k] != 'undefined') {
                        newValues[k] += parseFloat(vv[k]);
                    } else {
                        newValues[k] = parseFloat(vv[k]);
                    }
                });
            });
            $.each(newValues, function (k, v) {
                newValues[k] = parseFloat(v).toFixed(4);
            });
            if (series.length > lineSourceLength) {
                series[series.length - 1].data = newValues;
            } else {
                series.push({
                    name: 'FOF组合基金',
                    type: 'line',
                    data: newValues,
                    smooth: true,
                    lineStyle: {
                        normal: {opacity: 0.5}
                    }
                });
            }
            option.series = series;
            myChart.setOption(option);
        } catch (e) {
            alert(e.message);
        }
    }
};
for (var key in combinationGraph) {
    if (key) {
        exports[key] = combinationGraph[key];
    }
}